# -*- coding: utf-8 -*-
from flask import Flask, g, render_template, redirect, url_for, request, make_response
import os
import sqlite3
from flask_jsglue import JSGlue


app = Flask(__name__)
app.config['DATABASE'] = os.path.join(app.root_path, 'api.db')
jsglue = JSGlue()
jsglue.init_app(app)

@app.route('/<path:path>')
def test(path):
    dataList = fetch_data()
    for data in dataList:
        name = data['name']
        api = data['api']
        status = data['status']
        if path == api and status == 'on':
            with open('response/' + name, 'r') as f:
                content = f.read()
                response = make_response(content, 200)
                response.headers['content-type'] = 'application/json;charset=UTF-8'
                return response


def connect_db():
    return sqlite3.connect(app.config['DATABASE'])


def get_db():
    if not hasattr(g, 'db'):
        g.db = connect_db()
    return g.db


@app.route('/abc')
def testa():
    return 'abc'


@app.route('/switch_status/<id>/<status>')
def switch_status(id, status):
    db = get_db()

    db.execute('UPDATE apis SET status = (?) WHERE id = (?)', [status, id])
    db.commit()
    cur = db.cursor()

    if status == 'on':

        cur.execute('SELECT api FROM apis WHERE id = (?)', [id])
        m_api = cur.fetchall()[0][0]
        print m_api
        cur.execute('SELECT id FROM apis WHERE api = (?) AND id <> (?)', [m_api, id])
        ids = cur.fetchall()

        for i in ids:
            db.execute('UPDATE apis SET status = (?) WHERE id = (?)', [u'off', i[0]])
            db.commit()
        cur.close()

    cur = db.cursor()
    cur.execute('SELECT api,name FROM apis WHERE status = (?)', [u'on'])
    with open('mock_urls', 'w') as f:
        values = cur.fetchall()
        for index, a in enumerate(values):

            if index == len(values) - 1:
                f.writelines(a[0] + ":" + a[1])

            else:
                f.writelines(a[0] + ":" + a[1] + os.linesep)

    return redirect(url_for('api_list'))


@app.route('/initdb')
def init_db():
    with app.app_context():
        db = get_db()
        with app.open_resource('schema.sql', mode='r') as f:
            db.cursor().executescript(f.read())
        db.commit()
    return 'success'


@app.route('/insert')
def insert_testdata():
    db = get_db()
    db.execute('INSERT INTO apis (name,api,status) VALUES (?,?,?)', ['examinefinishall', 'examine/detail', 'off'])
    db.commit()

    return 'success'


def fetch_data():
    db = get_db()
    cur = db.cursor()
    cur.execute('SELECT name,api,status FROM apis')
    values = [dict(name=row[0], api=row[1], status=row[2]) for row in cur.fetchall()]
    return values


@app.route('/')
@app.route('/apilist')
def api_list():
    db = get_db()
    cur = db.cursor()
    cur.execute('SELECT id,name,api,status FROM apis')

    apis = [dict(id=row[0], name=row[1], api=row[2], status=row[3]) for row in cur.fetchall()]

    cur = db.cursor()
    cur.execute('SELECT id,name,api,status,isbool FROM fieldsetting')

    #fields = [dict(id=row[0], name=row[1], api=row[2], status=row[3], isbool=row[4]) for row in cur.fetchall()]

    fields = []
    for row in cur.fetchall():
        id = row[0]
        name = row[1]
        setting = {}
        isbool = row[4]
        with open('field/'+name,'r') as f:
            for line in f:

                line = line.strip('\r\n')


                key = line.split(':')[0].decode('utf-8')

                value = line.split(':')[1].decode('utf-8')

                if isbool:
                    c = db.cursor()
                    c.execute('SELECT fieldvalue from newfieldstable where fieldname = (?) and name = (?)',
                              [value, name])
                    try:
                        ischecked = c.fetchall()[0][0]
                    except:
                        ischecked = 0
                    setting[key] = [value, ischecked]
                else:
                    setting[key] = {}
                    radio_ischecked = 1
                    c = db.cursor()
                    fieldlist = value.split(',')
                    f_values = []
                    db_values = []
                    for field in fieldlist:
                        print 'field---',field
                        f_name = field.split(' ')[0]
                        f_value = field.split(' ')[1]
                        f_values.append(f_value)
                        c.execute('SELECT fieldvalue from newfieldstable where fieldname = (?) and name = (?)',
                              [f_name, name])
                        try:
                            db_value = str(c.fetchall()[0][0])
                            db_values.append(db_value)
                        except:
                            pass
                        setting[key].update({f_name:f_value})

                    for index,v in enumerate(f_values):
                        try:
                            if v == db_values[index]:
                                continue
                            else:
                                radio_ischecked = 0
                        except:
                            radio_ischecked = 0
                    setting[key].update({"radio_ischecked":radio_ischecked})

        field = {
            "id":row[0],
            "name" : row[1],
            "api" : row[2],
            "status" : row[3],
            "isbool":row[4],
            "setting":setting
        }

        fields.append(field)
    return render_template('apilist.html', apis=apis, fields=fields)





@app.route('/addapi')
def add_api():
    return render_template('addapi.html')


@app.route('/addaction', methods=['POST'])
def add_action():
    db = get_db()
    db.execute('INSERT INTO apis (name,api,status) VALUES (?,?,?)', [request.form['name'], request.form['api'], 'off'])
    db.commit()

    with open('response/' + request.form['name'], 'w') as f:
        f.write(request.form['json'].encode('utf-8'))
    return redirect(url_for('api_list'))


@app.route('/editapi/<id>')
def edit_api(id):
    db = get_db()

    cur = db.cursor()
    cur.execute('SELECT id,name,api FROM apis WHERE id = (?)', [id])
    values = cur.fetchall()[0]
    name = values[1]
    json = open('response/' + str(name), 'r').read()
    api = {
        "id": values[0],
        "name": name,
        "api": values[2],
        "json": json.decode('utf-8')
    }
    return render_template("editapi.html", api=api)


@app.route('/updateapi/<id>', methods=['POST'])
def update_action(id):
    db = get_db()
    name = request.form['name']
    api = request.form['api']
    json = request.form['json']
    db.execute('UPDATE apis SET name = (?) , api = (?) WHERE id = (?)', [name, api, id])
    db.commit()
    with open('response/' + name, 'w') as f:
        f.write(json.encode('utf-8'))
    return redirect(url_for('api_list'))


@app.route('/deleteapi/<id>')
def delete_api(id):
    db = get_db()
    db.execute('DELETE FROM apis WHERE id = (?)', [id])
    db.commit()
    return redirect(url_for('api_list'))


@app.route('/addfieldinfo', methods=['GET', 'POST'])
def add_field_info():
    print "$$$$$$$$$$$" + request.method

    if request.method == 'GET':
        return render_template('addfieldinfo.html')
    else:

        name = request.form['name']
        api = request.form['api']
        print "********"
        print request.form.getlist('isbool')
        isbool = request.form.getlist('isbool')
        if not isbool:
            isbool = False
        else:
            isbool = True

        status = u'off'
        setting = request.form['setting']

        db = get_db()
        db.execute('INSERT INTO fieldsetting(name,api,isbool,status) VALUES(?,?,?,?)', [name, api, isbool, status])
        db.commit()
        with open('field/' + name, 'w') as f:
            f.write(setting.encode('utf-8'))
        return redirect(url_for('api_list'))


@app.route('/editfieldinfo/<id>', methods=['GET', 'POST'])
def edit_fieldinfo(id):
    db = get_db()
    if request.method == 'GET':
        cur = db.cursor()
        cur.execute('SELECT id,name,api,isbool FROM fieldsetting WHERE id = (?)', [id])
        values = cur.fetchall()[0]
        name = values[1]
        setting = open('field/' + str(name), 'r').read()
        field = {
            "id": values[0],
            "name": name,
            "api": values[2],
            "isbool": values[3],
            "setting": setting.decode('utf-8')
        }

        return render_template("editfield.html", field=field)
    else:
        name = request.form['name']
        api = request.form['api']
        isbool = request.form.getlist('isbool')
        # isbool = request.form['isbool']
        setting = request.form['setting']
        print 'setting,,,,,',setting
        if not isbool:
            isbool = False
        else:
            isbool = True
        db.execute('UPDATE fieldsetting SET name = (?) , api = (?), isbool = (?) WHERE id = (?)',
                   [name, api, isbool, id])
        db.commit()
        with open('field/' + name, 'w') as f:
            f.write(setting.encode('utf-8'))
        return redirect(url_for('api_list'))

@app.route('/updatecheck/<name>/<path:api>/<fieldname>/<ischecked>')
def update_check(name,api,fieldname,ischecked):
    print "checked_________________________"+ischecked
    print type(ischecked)
    print api,fieldname,ischecked
    db = get_db()
    cur = db.cursor()
    cur.execute('select * from newfieldstable where api = (?) and fieldname = (?)',[api,fieldname])
    results = cur.fetchall()

    checkvalue = 1 if ischecked==u"true" else 0

    if len(results) == 0:
        db.execute('insert into newfieldstable(name,api,fieldname,fieldvalue) values(?,?,?,?)',[name,api,fieldname,checkvalue])
    else:
        db.execute('UPDATE newfieldstable set fieldvalue = (?) where api= (?) and fieldname = (?) and name= (?)',[checkvalue,api,fieldname,name])
    db.commit()
    update_field_file_for_on()
    return redirect(url_for('api_list'))

def update_field_file_for_on():
    db = get_db()
    cur = db.cursor()
    cur.execute('SELECT api FROM fieldsetting WHERE status = (?)', [u'on'])
    results = cur.fetchall()
    rules_list = []
    for result in results:

        api = result[0].encode('utf-8')

        c = db.cursor()
        c.execute('SELECT fieldname,fieldvalue FROM newfieldstable where api = (?)', [api])
        fields = c.fetchall()
        mock = []
        for field in fields:
            name = field[0]
            value = field[1]
            mock.append('$..{name}={value}'.format(name=name, value=value))
        rules = {
            'global': {},
            'api': {api: {'mock': mock}}
        }
        rules_list.append(str(rules))

    with open('mock_fields', 'w') as f:

        for index, rule in enumerate(rules_list):

            rule = rule.replace("'", '"')
            if index == len(rules_list) - 1:
                f.writelines(rule)

            else:
                f.writelines(rule + os.linesep)

@app.route('/switch_status_field/<id>/<status>')
def switch_status_field(id,status):
    db = get_db()

    db.execute('UPDATE fieldsetting SET status = (?) WHERE id = (?)', [status, id])
    db.commit()
    cur = db.cursor()

    if status == 'on':

        cur.execute('SELECT api FROM fieldsetting WHERE id = (?)', [id])
        m_api = cur.fetchall()[0][0]
        print m_api
        cur.execute('SELECT id FROM fieldsetting WHERE api = (?) AND id <> (?)', [m_api, id])
        ids = cur.fetchall()

        for i in ids:
            db.execute('UPDATE fieldsetting SET status = (?) WHERE id = (?)', [u'off', i[0]])
            db.commit()
            db.execute('UPDATE newfieldstable set fieldvalue = 0 WHERE name = (select name from fieldsetting where id = (?))',[i[0]])
            db.commit()
        cur.close()
    else:
        db.execute(
            'UPDATE newfieldstable set fieldvalue = 0 WHERE name = (select name from fieldsetting where id = (?))',id)
        db.commit()
    update_field_file_for_on()
    return redirect(url_for('api_list'))
@app.route('/updateradio/<name>/<path:api>/<fieldname_value>/<ischecked>')
def update_radio(name,api,fieldname_value,ischecked):
    print "checked_radio" + ischecked,fieldname_value
    print api, fieldname_value, ischecked
    fieldname_value = eval(fieldname_value.replace('@','\''))
    print type(fieldname_value)
    print api, fieldname_value, ischecked
    db = get_db()
    for fieldname,value in fieldname_value.items():
        if fieldname == 'radio_ischecked':
            continue
        cur = db.cursor()
        cur.execute('select * from newfieldstable where api = (?) and fieldname = (?)', [api, fieldname])
        results = cur.fetchall()
        print results
        checkvalue = 1 if ischecked == u"true" else 0
        print checkvalue
        if len(results) == 0:
            db.execute('insert into newfieldstable(name,api,fieldname,fieldvalue) values(?,?,?,?)',
                       [name, api, fieldname, value])
        else:
            db.execute('UPDATE newfieldstable set fieldvalue = (?) where api= (?) and fieldname = (?) and name= (?)',
                       [value, api, fieldname, name])
        db.commit()
    update_field_file_for_on()
    return redirect(url_for('api_list'))

def dict_to_str(mydict):

    return str(mydict).replace("'","@")
app.add_template_global(dict_to_str, 'dict_to_str')
if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
